package quizman.mappers;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import quizman.domain.Quiz;
import quizman.tdg.QuizTDG;

/**
 * 
 */

/**
 * @author Team0i
 *
 */
public class QuizMapper {
	public static Quiz find(String quizName) throws Exception {
		try {
			ResultSet rs = QuizTDG.find(quizName);
			if(!rs.next()) return null;
			Quiz quiz = new Quiz(quizName, rs.getDate("Start"),rs.getDate("End"));
			quiz.setLength(rs.getInt("Length"));
			quiz.setQuestions(QuestionMapper.getQuestions(quizName));
			return quiz;
		} catch (Exception e) {
			String msg = "Error in QuizMapper.find";
			throw new Exception(msg, e);
		}
	}
	
	public static List<Quiz> findAll() throws Exception {
		try {
			ResultSet rs = QuizTDG.findAll();
			List<Quiz> lq = new ArrayList<Quiz>();
			if(!rs.next()) return null;
			do {
				Quiz quiz = new Quiz(rs.getString("Quiz_Name"), rs.getDate("Start"),rs.getDate("End"));
				quiz.setLength(rs.getInt("Length"));
				quiz.setQuestions(QuestionMapper.getQuestions(quiz.getName()));
				lq.add(quiz);
			} while(rs.next());
			return lq;
		} catch (Exception e) {
			String msg = "Error in QuizMapper.findAll";
			throw new Exception(msg, e);
		}
	}
	
	public static void insert(Quiz q) throws Exception {
		try {
			QuizTDG.insert(q.getName(), q.getLength(), q.getStart(), q.getFinish());
		} catch (Exception e) {
			String msg = "Error in QuizMapper.insert";
			throw new Exception(msg,e);
		}
	}
	
	public static void update(Quiz q) throws Exception {
		try {
			QuizTDG.update(q.getName(), q.getLength(), q.getStart(), q.getFinish());
		} catch (Exception e) {
			String msg = "Error in QuizMapper.update";
			throw new Exception(msg,e);
		}
	}
	
	public static void delete(Quiz q) throws Exception {
		try {
			QuizTDG.delete(q.getName());
		} catch (Exception e) {
			String msg = "Error in QuizMapper.delete";
			throw new Exception(msg,e);
		}
	}
	
}
